import java.util.Random;

import javax.sound.midi.MidiDevice;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.Sequence;
import javax.sound.midi.Sequencer;
import javax.sound.midi.Track;
import javax.sound.midi.MidiDevice.Info;

import scales.ScalesEnum;

import midi.Chords;
import midi.MidiChord;
import midi.Pitch;
import midi.IntervalOperations.interval;


public class MidiTest3 {
	private static Sequencer sequencer;
	
	public static void main(String args[]){
		Pitch rootPitch = new Pitch(60);
		interval[] intervals = ScalesEnum.Major.getIntervals();
		
		final int count = 16;
		Pitch[] pitches = new Pitch[count];
		long[] lengths = new long[count];
		Chords[] chords = new Chords[count];
		
		Random rn = new Random();
		
		pitches[0] = rootPitch;
		lengths[0] = rn.nextInt(3) + 1;
		chords[0] = Chords.MajorTriad;
		
		for (int i = 1; i < count; i++){
			int scaleDegree = rn.nextInt(intervals.length);
			pitches[i] = rootPitch.raise(intervals[scaleDegree]);
			lengths[i] = rn.nextInt(3) + 1;
			chords[i] = Chords.MajorTriad;
		}
		
		
		MidiChord[] midiChords = new MidiChord[count];
		
		for (int i = 0; i < count; i++){
			midiChords[i] = chords[i].toMidiChord(pitches[i], 90, lengths[i]);
		}
		
		try{
			Info[] info = MidiSystem.getMidiDeviceInfo();
			MidiDevice loopBe = MidiSystem.getMidiDevice(info[3]);
			loopBe.open();
			System.out.println(info[3]);
			sequencer = MidiSystem.getSequencer(false);
			sequencer.getTransmitter().setReceiver(loopBe.getReceiver());
			sequencer.setTempoInBPM(60);
			sequencer.open();
			sequencer.setTempoFactor(1);
			
			
			
		
			Sequence sequence = new Sequence(Sequence.PPQ, 4);

			Track track = sequence.createTrack();
			
			long prevTicks = 0;
			
			for (MidiChord chord : midiChords){
				chord.addToTrack(track, 2, prevTicks);
				prevTicks += chord.getLength();
			}
			
			sequencer.setSequence(sequence);
			sequencer.setTickPosition(0);
			sequencer.start();

			Thread.sleep(10000);
			
			sequencer.stop();
		}
		catch (Exception e){
		}
	}
}
